﻿using IceDog.EFCore.Cmd.DBFirst.Models;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using System;
using System.Linq;

namespace IceDog.EFCore.Cmd.DBFirst
{
    class Program
    {
        static void Main(string[] args)
        {
            SaveData();
            QueryData();
            Console.ReadKey();
        }
        static void SaveData()
        {
            using (var db = new DioBlogContext())
            {
                var userIsExist = db.BlogUsers.Any(u => u.Account == "晓晨master");
                if (userIsExist) { return; }
                var user = new BlogUsers()
                {
                    Account = "晓晨master",
                    BlogUrl = "www.example.com/xiaochenmaster",
                };
                db.BlogUsers.Add(user);
                var count = db.SaveChanges();
                Console.WriteLine("{0} records saved to database", count);
                var article = new BlogArticles
                {
                    Author = user,
                    CreateTime = DateTime.Now,
                    Title = "EF Core 入门系列 1",
                    Content = "入门。。。。"
                };
                db.BlogArticles.Add(article);
                count = db.SaveChanges();
                Console.WriteLine("{0} records saved to database", count);
                var comment = new BlogComments()
                {
                    CommentTime = DateTime.Now,
                    Content = "大佬厉害",
                    Article = article,
                    Commenter = user
                };
                db.BlogComments.Add(comment);
                count = db.SaveChanges();
                Console.WriteLine("{0} records saved to database", count);
            }
        }
        static void QueryData()
        {
            //查询
            using (var db = new DioBlogContext())
            {
                var user = db.BlogUsers
                    .Include(u => u.BlogArticles)
                    .AsNoTracking()
                    .FirstOrDefault(u => u.Account == "晓晨master");
                if (user != null)
                {
                    var settings = new JsonSerializerSettings()
                    {
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                    };
                    Console.WriteLine("晓晨master的博客数据\r\n" + JsonConvert.SerializeObject(user, Formatting.Indented, settings));
                }
            }
        }
    }
}
